package sysinit

import (
	"strings"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
)

// consoleLogs开发模式下日志
var consoleLogs *logs.BeeLogger

// fileLogs 生产环境下日志
var fileLogs *logs.BeeLogger

//运行方式
var runmode string

func InitLogs() {
	consoleLogs = logs.NewLogger(1)
	consoleLogs.SetLogger(logs.AdapterConsole)
	//输出文件名和行号
	consoleLogs.EnableFuncCallDepth(true)
	consoleLogs.SetLogFuncCallDepth(5)

	consoleLogs.Async() //异步
	fileLogs = logs.NewLogger(1e4)
	level := beego.AppConfig.String("logs::level")
	filename := beego.AppConfig.String("logs::filename")

	fileLogs.EnableFuncCallDepth(true)
	consoleLogs.SetLogFuncCallDepth(5)
	//"separate":["error", "warning", "notice", "info","debug"],
	fileLogs.SetLogger(logs.AdapterMultiFile, `{"filename":"`+filename+`",
		"level":`+level+`,
		"daily":true,
		"maxdays":10,
		"color":true}`)
	fileLogs.Async() //异步
	runmode = strings.TrimSpace(strings.ToLower(beego.AppConfig.String("runmode")))
	if runmode == "" {
		runmode = "prod"
	}
}
func LogEmergency(v interface{}) {
	log("emergency", v)
}
func LogAlert(v interface{}) {
	log("alert", v)
}
func LogCritical(v interface{}) {
	log("critical", v)
}
func LogError(v interface{}) {
	log("error", v)
}
func LogWarning(v interface{}) {
	log("warning", v)
}
func LogNotice(v interface{}) {
	log("notice", v)
}
func LogInfo(v interface{}) {
	log("info", v)
}
func LogDebug(v interface{}) {
	log("debug", v)
}

func LogTrace(v interface{}) {
	log("trace", v)
}

//Log 输出日志
func log(level, v interface{}) {
	format := "%s"
	if level == "" {
		level = "debug"
	}
	if runmode == "prod" {
		switchLogLevel(format, v, level, fileLogs)
	}
	switchLogLevel(format, v, level, consoleLogs)
}

func switchLogLevel(format string, v interface{}, level interface{}, logs *logs.BeeLogger) {
	switch level {
	case "emergency":
		logs.Emergency(format, v)
	case "alert":
		logs.Alert(format, v)
	case "critical":
		logs.Critical(format, v)
	case "error":
		logs.Error(format, v)
	case "warning":
		logs.Warning(format, v)
	case "notice":
		logs.Notice(format, v)
	case "info":
		logs.Info(format, v)
	case "debug":
		logs.Debug(format, v)
	case "trace":
		logs.Trace(format, v)
	default:
		logs.Debug(format, v)
	}
}
